package mundomensajero.main;


import java.util.ArrayList;

import mundomensajero.data.FavoritesSQLiteHelper;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class FavoritesView extends Activity {
	ListView lv;
    ArrayList<DestinatarioData> data = new ArrayList<DestinatarioData>();
    EditText txtNom,txtNum;
    Button btnAceptar,btnCancelar;
    Dialog dialog;
    SQLiteDatabase db;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_viewfavorites);
        lv = (ListView)findViewById(R.id.LstFavorites);

        FavoritesSQLiteHelper usdbh = new FavoritesSQLiteHelper(this, "DBFavorites_MM", null, 1);
        db = usdbh.getWritableDatabase();
        
        favoritesLoad();     
    }
    
    /**=============================================================================================**/
    /**									FUNCIONES DE BOTONES										**/
    /**=============================================================================================**/
   
	 
	 public void Actualizar(){
		 String sql;
		 for(int i=0; i<data.size();i++){
			if(!data.get(i).enviarmsj()){
				sql = "DELETE FROM Favorites WHERE numero='"+data.get(i).getNumero().toString()+"'";
				db.execSQL(sql);
			}
		}
		//db.close();
	 	favoritesLoad();
	 }
	 
	 public void Regresar(){
	 		Intent principal = new Intent();
			principal.setClass(this,MundoMensajero_Activity.class);
			setResult(RESULT_CANCELED, principal);
			
			//Actualizamos los favoritos antres de salir
			String sql;
			 for(int i=0; i<data.size();i++){
				if(!data.get(i).enviarmsj()){
					sql = "DELETE FROM Favorites WHERE numero='"+data.get(i).getNumero().toString()+"'";
					db.execSQL(sql);
				}
			}
			
			db.close();
			finish();
	 }
    
	 private OnClickListener onclickAgregarFavADest = new OnClickListener() {
         public void onClick(View v) {
        	 int pos = lv.getPositionForView(v);
        	 if(pos !=  ListView.INVALID_POSITION)
        		 regresar(data.get(pos).getNombre(),data.get(pos).getNumero());
         }
     };
     private OnClickListener onClickCancelar = new OnClickListener() {
         public void onClick(View v) {
             dismissDialog(0);
             txtNom.setText("");
             txtNum.setText("");
         }
     };
     private OnClickListener onClickAceptar = new OnClickListener() {
         public void onClick(View v) {
             procesarAceptar();
         }
     };
     
     
     /**=================================================================================**/
     /**								FUNCIONES DE MENUS									**/
     /**=================================================================================**/
     
    
     @Override  
     public boolean onCreateOptionsMenu(Menu menu) {
         MenuInflater inflater = getMenuInflater();
         inflater.inflate(R.menu.favorite_menu, menu);
         return true;
     }
     
   
     @Override    
     public boolean onOptionsItemSelected(MenuItem item) {
         switch (item.getItemId()) {
             case R.id.nuevoFav:
             	showDialog(0);
             	return true;
             case R.id.regresarFav:
            	 Regresar();
             	return true;
             case R.id.contactosFav:
            	 Intent contactos = new Intent();
             	contactos.setClass(this, ContactView.class);
             	startActivityForResult(contactos, 1);
             	return true;
             case R.id.actualizarFav:
             	Actualizar();
             	return true;
             default:
                 return super.onOptionsItemSelected(item);
         }
     }
     
     protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 		if(requestCode == 1){
 			if (resultCode == RESULT_OK){
 				String nombre = sacarNombre(data.getStringExtra("contact"));
 				String numero = data.getStringExtra("number");
 				
 				String[] campos = new String[] {"nombre"};
 		    	String[] args = new String[] {numero};
 		    	Cursor c = db.query("Favorites", campos, "numero=?", args, null, null, null);

 		    	if(c.moveToFirst()){
 		    		Toast.makeText(this,"El "+numero+" ya está en favoritos", Toast.LENGTH_SHORT).show();
 		    	}
 		    	else{
 		    		ContentValues nuevoRegistro = new ContentValues();
 		    		nuevoRegistro.put("numero", numero);
 		    		nuevoRegistro.put("nombre", nombre);
 		    		db.insert("Favorites", null, nuevoRegistro);
 		    		favoritesLoad();
 		    	}
 			}	    		
 				
 			}else if(resultCode == RESULT_CANCELED){
 				//Toast.makeText(this, "CANCEL", Toast.LENGTH_LONG).show();
 			}
 		
 		} 
     
     
     	 
     /**============================================================================================**/
     /**									FUNCIONES PROPIAS										**/
     /**============================================================================================**/
	 
	public String sacarNombre(String n){
	   	String nombre[] = n.split(" ");
	   	if(nombre[0].length()>2) return nombre[0];
	   	else return nombre[1];
	}
   

    private void favoritesLoad(){
    	String[] campos = new String[] {"numero", "nombre"};
    	Cursor c = db.query("Favorites", campos, null, null, null, null, "nombre ASC");
    	data.clear();
    	if (c.moveToFirst()) {
    	     do {
    	    	 data.add(new DestinatarioData(c.getString(1), c.getString(0), true));
    	     } while(c.moveToNext());
    	}
    	AdaptadorDestinatarios adaptador = new AdaptadorDestinatarios(this);
   		lv.setAdapter(adaptador);
   		//db.close();
  		return;
    }
    
    public void msj(String s){
    	Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
    }
    
    public void procesarAceptar(){
    	if(txtNom.getText().length()==0){
    		Toast.makeText(this,"Escribe el nombre", Toast.LENGTH_SHORT).show();
    		return;
    	}
    	else if(txtNum.getText().length()!=8){
    		Toast.makeText(this,"El número debe tener 8 dígitos", Toast.LENGTH_SHORT).show();
    		return;
    	}
    	else if(txtNum.getText().charAt(0)!='7'){
    		Toast.makeText(this,"El número debe empezar con 7", Toast.LENGTH_SHORT).show();
    		return;
    	}
    	String[] campos = new String[] {"nombre"};
    	String[] args = new String[] {txtNum.getText().toString()};
    	Cursor c = db.query("Favorites", campos, "numero=?", args, null, null, null);

    	if(c.moveToFirst()){
    		Toast.makeText(this,"El "+txtNum.getText()+" ya está en favoritos", Toast.LENGTH_SHORT).show();
    		dismissDialog(0);
    	}
    	else{
    		ContentValues nuevoRegistro = new ContentValues();
    		nuevoRegistro.put("numero", txtNum.getText().toString());
    		nuevoRegistro.put("nombre", txtNom.getText().toString());
    		db.insert("Favorites", null, nuevoRegistro);
    		txtNom.setText("");
    		txtNum.setText("");
    		favoritesLoad();
    		dismissDialog(0);
    	}
    	//db.close();
    }
    
    void regresar(String nom, String num){
    	Intent principal = new Intent();
 		principal.setClass(this,MundoMensajero_Activity.class);
 		principal.putExtra("number", num);
 		principal.putExtra("contact", nom);
 		setResult(RESULT_OK, principal);
 		
 		//Antes de irnos de este Activity actualizamos
 		String sql;
		 for(int i=0; i<data.size();i++){
			if(!data.get(i).enviarmsj()){
				sql = "DELETE FROM Favorites WHERE numero='"+data.get(i).getNumero().toString()+"'";
				db.execSQL(sql);
			}
		}
 		
 		
 		db.close();
 		finish();
    }
    
    /**=========================================================================================**/
    /**											ADAPTER											**/
    /**=========================================================================================**/
    
 
    private class AdaptadorDestinatarios extends BaseAdapter {
    	Activity context;

    	AdaptadorDestinatarios(Activity context) {
    		super();
    		this.context = context;
    	}
    	
    	public int getCount() {
    		return data.size();
    	}
    	 
    	public String getItem(int position) {
    		return data.get(position).toString();
    	}
    	 
    	public long getItemId(int position) {
    		return position;
    	}
    	 
    	public View getView(final int position, View convertView, ViewGroup parent) {
    		LayoutInflater inflater = context.getLayoutInflater();
    		View item = inflater.inflate(R.layout.favoritelist, null);
    		final CheckBox cb = (CheckBox)item.findViewById(R.id.checkfavorite);
    		Button btn = (Button)item.findViewById(R.id.btnAgregarFavADest);
    		
    		cb.setText(data.get(position).getNombre()+"\n"+data.get(position).getNumero());
    		cb.setChecked(data.get(position).enviarmsj());
    		btn.setOnClickListener(onclickAgregarFavADest);
    		
    		cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
    			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    				int i;
    				for(i=0;i<data.size(); i++){
    					if(cb.getText().toString().contains(data.get(i).getNumero())) break;
    				}
    	        	if(isChecked){
    	        		data.set(i, new DestinatarioData(data.get(i).getNombre(), data.get(i).getNumero(), true));
    	        	}
    	        	else{
    	        		msj("Se eliminara a "+data.get(i).getNombre().toString()+" de favoritos");
    	        		data.set(i, new DestinatarioData(data.get(i).getNombre(), data.get(i).getNumero(), false));
    	        	}
    			}
    		});
    		return item;
    	}
    	 
    	}
    	 
    	public static class ViewHolder {
    		public CheckBox chkItem;
    	}
    	 
    	
    	@Override
    	protected Dialog onCreateDialog(int id) {
    	 // TODO Auto-generated method stub
    	 Dialog dialog = null;;
    	    switch(id) {
	    	    case 0:
		    	     dialog = new Dialog(FavoritesView.this);
		    	     dialog.setTitle("\t\t   Nuevo Favorito");
		    	     dialog.setContentView(R.layout.newfavorite);
		    	     txtNom = (EditText)dialog.findViewById(R.id.txtNombre);
		    	     txtNum = (EditText)dialog.findViewById(R.id.txtNumero);
		    	     btnCancelar = (Button)dialog.findViewById(R.id.btnCancelar);
		    	     btnAceptar = (Button)dialog.findViewById(R.id.btnAceptar);
		    	     btnCancelar.setOnClickListener(onClickCancelar);
		    	     btnAceptar.setOnClickListener(onClickAceptar);
	    	     break;
    	    }
    	    return dialog;
    	}
    	
    	@Override
        public boolean onKeyDown(int keyCode, KeyEvent event){   
        	
        	if(keyCode == KeyEvent.KEYCODE_BACK){
        		Regresar();
        		return true;
        	}
    		return super.onKeyDown(keyCode, event);
        }
    
}
